using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections;
using System.Globalization;
using MBLocale;

/// <summary>
/// Summary description for GenerateAlerts
/// </summary>
public class GenerateAlerts
{
    string strErrMessage = "";
    HDDatabase HDD;
    DynamicDisplayI DDI;
    SqlCommand sqlcmd;
    ArrayList arrSqlCmd = new ArrayList();
    ScreenReader SR;
    string usr_id = "";
    public GenerateAlerts()
    {
        if (HttpContext.Current != null && HttpContext.Current.Session != null)
        {
            if (HttpContext.Current.Session["user_afrowid"] != null)
            {

                usr_id = HttpContext.Current.Session["user_afrowid"].ToString();
            }
        }

    }

    public void GenerateAlert()
    {

        HDD = new HDDatabase();
        try
        {
            DataTable alert_generate = HDD.GetDataTable("select * from sy_alert_generation where user_id='" + usr_id + "'");

            ////check user from Assign Type-User
            //string sql = "select a.af_row_id,a.status,a.finish_date,b.assign_type from sy_task_config a,sy_assign_task b where a.status <> 'CO'  and a.af_row_id=b.task_row_id and b.assign_type='usr' ";

            //sql += " and b.assign_type_id='" + usr_id + "' and  CONVERT(VARCHAR(10),a.finish_date,111) <= CONVERT(VARCHAR(10),GETUTCDATE(),111)";
            //DataTable dt = HDD.GetDataTable(sql);
            //// check user from Assign Type-Role
            //sql = " select a.af_row_id,a.status,a.finish_date,b.assign_type from sy_task_config a,sy_assign_task b where a.status <> 'CO' and a.af_row_id=b.task_row_id and b.assign_type='role'";
            //sql += "and b.assign_type_id in (select role_id from sy_usr_rol where user_id='" + usr_id + "') and  CONVERT(VARCHAR(10),a.finish_date,111) <= CONVERT(VARCHAR(10),GETUTCDATE(),111)";

            //DataTable dt_role_ids = HDD.GetDataTable(sql);
            //if (dt_role_ids.Rows.Count > 0)
            //{
            //    dt.Merge(dt_role_ids, true);

            //}

            //sql = " select a.af_row_id,a.status,a.finish_date,b.assign_type from sy_task_config a,sy_assign_task b where a.status <> 'CO' and a.af_row_id=b.task_row_id and b.assign_type='bu'";
            //sql += "and b.assign_type_id in (select a.af_row_id from sy_bu a,sy_usr b where b.af_row_id='" + usr_id + "' and b.bu_id=a.bu_id) and  CONVERT(VARCHAR(10),a.finish_date,111) <= CONVERT(VARCHAR(10),GETUTCDATE(),111)";

            //DataTable dt_bu = HDD.GetDataTable(sql);
            //if (dt_bu.Rows.Count > 0)
            //{
            //    dt.Merge(dt_bu, true);

            //}
            //Commented and changed by Sampath on 21-Apr-2012 
            string sql = "select a.af_row_id,a.status,a.finish_date,b.assign_type from sy_task_config a,sy_assign_task b where a.status <> 'CO'  and a.af_row_id=b.task_row_id and b.assign_type='usr'  and b.assign_type_id='" + usr_id + "' union "
                + "select a.af_row_id,a.status,a.finish_date,b.assign_type from sy_task_config a,sy_assign_task b where a.status <> 'CO' and a.af_row_id=b.task_row_id and b.assign_type='role'and b.assign_type_id in (select role_id from sy_usr_rol where user_id='" + usr_id + "') "
                + "union select a.af_row_id,a.status,a.finish_date,b.assign_type from sy_task_config a,sy_assign_task b where a.status <> 'CO' and a.af_row_id=b.task_row_id and b.assign_type='bu'and b.assign_type_id in (select a.af_row_id from sy_bu a,sy_usr b where b.af_row_id='" + usr_id + "' and b.bu_id=a.bu_id) ";
            DataTable dt = HDD.GetDataTable(sql);
            //DataTable dtNew = setUserDate(dt); // Commented by 'Imran Gani' on 18-Sep-2013, to handle over due days

            CheckTaskExist(dt, alert_generate);
            CheckUserID(dt, alert_generate);
            HDD.ExecuteTransaction(arrSqlCmd);
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : GenerateAlerts : " + ex.Message);
        }
        finally
        {
            HDD = null;
        }
    }

    //function added by Sampath on 22-Apr-2012
    private DataTable setUserDate(DataTable dt)
    {
        DataTable dtNew = dt.Clone();
        try
        {
            DDI = new DynamicDisplayI();
            Localization loc = new Localization();
            string strUTCoffset = DDI.getUserSetting("sy_usr", "time_zone", "sy_timezone", "utc_offset", "timezone_id");
            //DateTime current_date = DateTime.Parse(loc.getDateTime4TimeZone(TimeZone.CurrentTimeZone.ToLocalTime(DateTime.Now).ToString(loc.getUserCulture()), strUTCoffset, true, false));  // Commented by 'Imran Gani' on 28-Feb-2014, for MBLocale
            CultureInfo ci = MBLocalization.getCultureInfo(HttpContext.Current.Session["userlocale"].ToString());
            DateTime current_date = DateTime.Parse(loc.getDateTime4TimeZone(TimeZone.CurrentTimeZone.ToLocalTime(DateTime.Now).ToString(ci), strUTCoffset, true, false));

            foreach (DataRow dr in dt.Rows)
            {
                //DateTime drDate = DateTime.Parse(loc.getDateTime4TimeZone(dr["finish_date"].ToString(), strUTCoffset, false, false), loc.getUserCulture()); // Commented by 'Imran Gani' on 28-Feb-2014, for MBLocale
                DateTime drDate = DateTime.Parse(loc.getDateTime4TimeZone(dr["finish_date"].ToString(), strUTCoffset, false, false), ci);
                if (drDate.Date >= current_date.Date)
                    dtNew.ImportRow(dr);
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : setUserDate : " + ex.Message);
        }
        return dtNew;
    }

    #region Old code commented by 'Imran Gani' on 28-Feb-2014, for MBLocale
    //private string GetUserTime(string input, string strUTCoffset, bool isForStoring)
    //{
    //    string sValue = "";
    //    string timeZoneOffest = strUTCoffset;
    //    DynamicDisplayI ddi = new DynamicDisplayI();
    //    Localization loc = new Localization();
    //    string sDateTimeFormatString = loc.getDateFormat() + " hh:mm tt";
    //    DateTime dt = new DateTime();
    //    try
    //    {
    //        string sHours = "";
    //        string sMinutes = "";
    //        bool isSystem = false;
    //        // if (input == "") return input;
    //        if (timeZoneOffest != "")
    //        {
    //            if (isForStoring)
    //            {
    //                if (timeZoneOffest.StartsWith("-"))
    //                    timeZoneOffest = "+" + timeZoneOffest.Substring(1);
    //                else if (timeZoneOffest.StartsWith("+"))
    //                    timeZoneOffest = "-" + timeZoneOffest.Substring(1);
    //                else if (timeZoneOffest.Trim() != "0")
    //                    timeZoneOffest = "+" + timeZoneOffest;
    //            }
    //            if (timeZoneOffest.IndexOf('.') != -1)
    //            {
    //                sHours = timeZoneOffest.Substring(1, timeZoneOffest.IndexOf('.') - 1);
    //                sMinutes = timeZoneOffest.Substring(timeZoneOffest.IndexOf('.') + 1, timeZoneOffest.Length - timeZoneOffest.IndexOf('.') - 1);
    //            }
    //            else
    //                sHours = timeZoneOffest.Substring(1, timeZoneOffest.Length - 1);

    //            if (timeZoneOffest.StartsWith("-"))
    //            {
    //                sHours = "-" + sHours;
    //                if (sMinutes != "")
    //                    sMinutes = "-" + sMinutes;
    //            }
    //        }
    //        if (sHours == "") sHours = "0";
    //        if (isForStoring)
    //            dt = DateTime.Parse(input, loc.getUserCulture());
    //        else
    //            dt = DateTime.Parse(input); //DateTime.Parse(input);//sanal on Sept 04, 2008
    //        dt = dt.AddHours(Convert.ToDouble(sHours));
    //        if (sMinutes != "")
    //            dt = dt.AddMinutes(Convert.ToDouble(sMinutes));
    //        if (isForStoring)
    //            sValue = dt.ToUniversalTime().ToString();
    //        else
    //            sValue = isSystem == true ? dt.ToString(sDateTimeFormatString) : dt.ToLocalTime().ToString(sDateTimeFormatString); //dt.ToString(sDateTimeFormatStrin
    //        //sValue = dt.ToUniversalTime().ToString(CultureInfo.InvariantCulture);
    //        //else
    //        // sValue = isSystem == true ? dt.ToString(sDateTimeFormatString) : dt.ToLocalTime().ToString(sDateTimeFormatString);
    //    }
    //    catch (Exception ex)
    //    {
    //        LogWriter.WriteLog("getInvariantDateTime : Error : " + ex.Message);
    //        sValue = "";
    //    }
    //    return sValue;
    //}
    #endregion

    public System.Globalization.CultureInfo getUserCulture()
    {
        if (HttpContext.Current.Session["userlocale"] == null)
            return new CultureInfo("");
        System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo(HttpContext.Current.Session["userlocale"].ToString());
        return ci;
    }

    void CheckUserID(DataTable UserTask, DataTable AlertGenerated)
    {
        HDD = new HDDatabase();
        try
        {
            // DataTable alert_generate = HDD.GetDataTable("select * from sy_alert_generation where user_id='" + StrUsrID + "'");
            if (AlertGenerated.Rows.Count > 0)
            {
                for (int i = 0; i < AlertGenerated.Rows.Count; i++)
                {
                    bool blassignto = false;
                    // DataTable assign_to = HDD.GetDataTable("select * from sy_assign_task where task_row_id='" + AlertGenerated.Rows[i]["task_row_id"] + "'");
                    for (int j = 0; j < UserTask.Rows.Count; j++)
                    {
                        if (AlertGenerated.Rows[i]["task_row_id"].ToString() == UserTask.Rows[j]["af_row_id"].ToString())
                        {
                            blassignto = true;
                        }
                    }
                    if (blassignto == false)
                    {
                        //string update = "Update  sy_alert_generation set alert_status='Inactive' where user_id='" + StrUsrID + "' and task_row_id='" + alert_generate.Rows[i]["task_row_id"] + "'";
                        string delete = " Delete from sy_alert_generation where user_id='" + usr_id + "' and task_row_id='" + AlertGenerated.Rows[i]["task_row_id"] + "'";
                        sqlcmd = new SqlCommand(delete);
                        HDD.ExecuteCmdObj(sqlcmd);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : Delete User Ids removed from task : " + ex.Message);
        }
        finally
        {
            // HDD = null;
        }
    }

    void CheckTaskExist(DataTable UserTask, DataTable AlertGenerated)
    {
        HDD = new HDDatabase();
        try
        {
            if (AlertGenerated.Rows.Count > 0)
            {
                foreach (DataRow dr in UserTask.Rows)
                {
                    bool blExists = false;

                    for (int i = 0; i < AlertGenerated.Rows.Count; i++)
                    {
                        if (dr["af_row_id"].ToString() == AlertGenerated.Rows[i]["task_row_id"].ToString())
                        {
                            blExists = true;
                        }
                    }
                    if (blExists == false)
                    {
                        int rowcount = UserTask.Rows.IndexOf(dr);
                        //commented by Sampath on 22-Apr-2012
                        //DateTime finish_time = Convert.ToDateTime(UserTask.Rows[rowcount]["finish_date"].ToString());
                        //if (finish_time.Date <= DateTime.Now.Date)
                        insert(UserTask, rowcount);
                        // HDD.ExecuteTransaction(arrSqlCmd);
                    }
                }
            }
            else
                if (UserTask.Rows.Count > 0)
                {
                    for (int i = 0; i < UserTask.Rows.Count; i++)
                    {
                        insert(UserTask, i);
                    }
                }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : Inserting New task in alert generation: " + ex.Message);
        }
        finally
        {
            // HDD = null;
        }
    }
    private void insert(DataTable dt, int inr_row)
    {
        // usr_id = HttpContext.Current.Session["user_afrowid"].ToString();
        SR = new ScreenReader();
        string strinsert = " INSERT into sy_alert_generation (af_row_id,task_row_id,user_id,created_by,created_at,modified_at,modified_by,owner_id,task_source,alert_status) values (@af_row_id,@task_row_id,@user_id,@created_by,@created_at,@modified_at,@modified_by,@owner_id,@task_source,@alert_status)";
        sqlcmd = new SqlCommand(strinsert);
        sqlcmd.Parameters.Add("@af_row_id", System.Data.SqlDbType.NVarChar).Value = SR.getHashKey();
        sqlcmd.Parameters.Add("@task_row_id", System.Data.SqlDbType.NVarChar).Value = dt.Rows[inr_row]["af_row_id"];
        sqlcmd.Parameters.Add("@user_id", System.Data.SqlDbType.NVarChar).Value = usr_id;
        sqlcmd.Parameters.Add("@created_by", System.Data.SqlDbType.NVarChar).Value = usr_id;
        sqlcmd.Parameters.Add("@modified_by", System.Data.SqlDbType.NVarChar).Value = usr_id;
        sqlcmd.Parameters.Add("@created_at", System.Data.SqlDbType.DateTime).Value = DateTime.Now.ToString();
        sqlcmd.Parameters.Add("@modified_at", System.Data.SqlDbType.DateTime).Value = DateTime.Now.ToString();
        sqlcmd.Parameters.Add("@owner_id", System.Data.SqlDbType.NVarChar).Value = usr_id;
        sqlcmd.Parameters.Add("@task_source", System.Data.SqlDbType.NVarChar).Value = dt.Rows[inr_row]["assign_type"].ToString();
        sqlcmd.Parameters.Add("@alert_status", System.Data.SqlDbType.NVarChar).Value = "active";
        arrSqlCmd.Add(sqlcmd);

    }

    public GridView LoadGrid(GridView Reminders)
    {
        try
        {
            Reminders.DataSource = new DataView(getTaskReminderData());
            Reminders.DataBind();
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : LoadGrid : " + ex.Message);
        }
        return Reminders;
    }

    public DataTable getTaskReminderData()
    {
        HDDatabase HDD = new HDDatabase();
        DynamicDisplayI ddi = new DynamicDisplayI();
        Localization loc = new Localization();
        DataTable dtNew = new DataTable();
        string strUTCoffset = "";
        try
        {
            DataTable dt = HDD.GetDataTable("select * from sy_alert_generation where user_id='" + usr_id + "'");
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    if (dr["alert_status"].ToString() == "dismiss")
                    {
                        arrSqlCmd.Clear();
                        string strStatus = HDD.GetColumnValue("select status from sy_task_config where af_row_id='" + dr["task_row_id"].ToString() + "';");
                        if (strStatus == "CO")
                        {
                            string strDelete = "delete from sy_alert_generation where af_row_id='" + dr["af_row_id"].ToString() + "'";
                            sqlcmd = new SqlCommand(strDelete);
                            arrSqlCmd.Add(sqlcmd);
                            HDD.ExecuteTransaction(arrSqlCmd);
                        }
                    }
                }
            }
            strUTCoffset = ddi.getUserSetting("sy_usr", "time_zone", "sy_timezone", "utc_offset", "timezone_id");
            //Code changed by Sampath on 21-Apr-2012
            //dt = HDD.GetDataTable("select a.af_row_id,a.task_source,a.alert_status,a.deferred_time,b.subject,b.af_row_id as task_row_id,b.status ,b.finish_date from sy_alert_generation a , sy_task_config b where a.task_row_id = b.af_row_id and a.user_id='" + usr_id + "' and alert_status in('active','deferred') and CONVERT(VARCHAR(10),b.finish_date,111) <= CONVERT(VARCHAR(10),GETUTCDATE(),111)  order by   finish_date asc");
            dt = HDD.GetDataTable("select a.af_row_id,a.task_source,a.alert_status,a.deferred_time,b.subject,b.af_row_id as task_row_id,b.status ,b.finish_date from sy_alert_generation a , sy_task_config b where a.task_row_id = b.af_row_id and a.user_id='" + usr_id + "' and alert_status in('active','deferred') order by finish_date asc");
            if (dt != null && dt.Rows.Count > 0)
            {
                //Code added by Sampath on 21-Apr-2012
                //dtNew = setUserDate(dt); // Commented by 'Imran Gani' on 18-Sep-2013, to handle over due days
                dtNew = dt.Copy(); // Added by 'Imran Gani' on 18-Sep-2013, to handle over due days
                for (int i = 0; i < dtNew.Rows.Count; i++)//dt
                {
                    if (dtNew.Rows[i]["alert_status"].ToString().ToLower() == "deferred") //dt
                    {
                        if (dtNew.Rows[i]["deferred_time"].ToString() != "") //dt
                        {
                            DateTime finish_time = Convert.ToDateTime(dtNew.Rows[i]["deferred_time"].ToString());
                            string Now = Convert.ToString(DateTime.Now.ToUniversalTime());
                            Now = loc.getDateTime4TimeZone(Now, strUTCoffset, false, false);
                            //Changed by Sampath on 21-Apr-2012
                            //DateTime now = Convert.ToDateTime(Now);
                            //DateTime now = DateTime.Parse(Now, loc.getUserCulture()); // Commented by 'Imran Gani' on 28-Feb-2014, for MBLocale
                            DateTime now = DateTime.Parse(Now, MBLocalization.getCultureInfo(HttpContext.Current.Session["userlocale"].ToString())); // Added by 'Imran Gani' on 28-Feb-2014, for MBLocale
                            //DateTime now = DateTime.Now.ToUniversalTime();
                            if (finish_time >= now)
                                dtNew.Rows[i].Delete(); //dt
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : Load Task : " + ex.Message);
        }
        finally
        {
            HDD = null;
            ddi = null;
            loc = null;
        }
        return dtNew;
    }
    
    public bool DismissTask(string Row_id)
    {
        bool dismiss = true;
        HDDatabase HDD = new HDDatabase();
        // string User_id = HttpContext.Current.Session["user_afrowid"].ToString();
        try
        {
            string strUpdateStatus = "update sy_alert_generation set alert_status ='dismiss' where af_row_id='" + Row_id + "' and user_id='" + usr_id + "'";

            sqlcmd = new SqlCommand(strUpdateStatus);
            arrSqlCmd.Add(sqlcmd);
            if (!HDD.ExecuteTransaction(arrSqlCmd))
            {
                dismiss = false;
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : Dismiss Task : " + ex.Message);
        }
        finally
        {
            HDD = null;

        }
        return dismiss;
    }

    public bool DeferTask(string Row_id, string deferred)
    {
        HDDatabase HDD = new HDDatabase();
        DynamicDisplayI ddi = new DynamicDisplayI();
        Localization loc = new Localization();
        arrSqlCmd.Clear();

        bool defer = true;
        try
        {
            string strUTCoffset = "";
            strUTCoffset = ddi.getUserSetting("sy_usr", "time_zone", "sy_timezone", "utc_offset", "timezone_id");

            string finish_date = Convert.ToString(DateTime.Now.ToUniversalTime());
            finish_date = loc.getDateTime4TimeZone(finish_date, strUTCoffset, false, false);
            //DateTime finish_dt = Convert.ToDateTime(finish_date);
            //DateTime finish_dt = DateTime.Parse(finish_date, loc.getUserCulture()); // Commented by 'Imran Gani' on 28-Feb-2014, for MBLocale
            DateTime finish_dt = DateTime.Parse(finish_date, MBLocalization.getCultureInfo(HttpContext.Current.Session["userlocale"].ToString())); // Added by 'Imran Gani' on 28-Feb-2014, for MBLocale
            finish_dt = finish_dt.AddMinutes(Convert.ToDouble(deferred));
            string date = finish_dt.Year + "-" + finish_dt.Month + "-" + finish_dt.Day + " " + finish_dt.Hour + ":" + finish_dt.Minute + ":" + finish_dt.Second + ".000";
            string str_update_is_defer = "update sy_alert_generation set alert_status='deferred',deferred_time='" + date + "'  where af_row_id='" + Row_id + "' and user_id='" + usr_id + "'";
            sqlcmd = new SqlCommand(str_update_is_defer);
            arrSqlCmd.Add(sqlcmd);
            if (!HDD.ExecuteTransaction(arrSqlCmd))
            {
                defer = false;

            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : Defer Task : " + ex.Message);
        }
        finally
        {
            HDD = null;
            ddi = null;
            loc = null;

        }
        return defer;
    }

    //Added by 'Imran Gani' on 07-Jan-2014, for complete button updated process
    public bool CompleteTask(string Row_id)
    {
        bool dismiss = true;
        HDDatabase HDD = new HDDatabase();
        // string User_id = HttpContext.Current.Session["user_afrowid"].ToString();
        try
        {
            string strUpdateStatus = "update [sy_task_config] set [status] ='CO' where [af_row_id] in (select [task_row_id] from [sy_alert_generation] where [af_row_id] = '" + Row_id + "' and [user_id] = '" + usr_id + "');";
            sqlcmd = new SqlCommand(strUpdateStatus);
            arrSqlCmd.Add(sqlcmd);
            if (!HDD.ExecuteTransaction(arrSqlCmd))
                dismiss = false;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : CompleteTask Task : " + ex.Message);
        }
        finally
        {
            HDD = null;
        }
        return dismiss;
    }
}
